// 主应用类
class LiveStreamApp {
  constructor() {
    this.localVideo = document.getElementById("localVideo");
    this.remoteVideo = document.getElementById("remoteVideo");
    this.startBtn = document.getElementById("startBtn");
    this.stopBtn = document.getElementById("stopBtn");
    this.cameraToggle = document.getElementById("cameraToggle");
    this.joinBtn = document.getElementById("joinBtn");
    this.leaveBtn = document.getElementById("leaveBtn");
    this.status = document.getElementById("status");
    this.streamUrl = document.getElementById("streamUrl");
    this.streamInfo = document.getElementById("streamInfo");
    this.currentStreamId = document.getElementById("currentStreamId");
    this.copyStreamId = document.getElementById("copyStreamId");
    this.playPrompt = document.getElementById("playPrompt");
    this.manualPlayBtn = document.getElementById("manualPlayBtn");

    this.localStream = null;
    this.isStreaming = false;
    this.currentCamera = "user"; // 'user' for front camera, 'environment' for back camera

    this.webRTC = new WebRTCManager();
    // this.chat = new ChatManager();

    this.init();
  }

  init() {
    this.bindEvents();
    this.updateStatus("ready", "准备就绪");
    this.hideStreamInfo(); // 初始化时隐藏直播间信息
    console.log("直播应用初始化完成");
  }

  bindEvents() {
    this.startBtn.addEventListener("click", () => this.startStreaming());
    this.stopBtn.addEventListener("click", () => this.stopStreaming());
    this.cameraToggle.addEventListener("click", () => this.toggleCamera());
    this.joinBtn.addEventListener("click", () => this.joinStream());
    this.leaveBtn.addEventListener("click", () => this.leaveStream());
    this.copyStreamId.addEventListener("click", () =>
      this.copyStreamIdToClipboard()
    );
    this.manualPlayBtn.addEventListener("click", () => this.manualPlayVideo());

    // 页面关闭时清理资源
    window.addEventListener("beforeunload", () => {
      this.cleanup();
    });
  }

  // 开始直播
  async startStreaming() {
    try {
      this.updateStatus("connecting", "获取摄像头权限...");

      // 获取摄像头权限
      this.localStream = await this.getCameraStream();
      this.localVideo.srcObject = this.localStream;

      // 连接到服务器
      await this.webRTC.connect();

      // 设置直播间ID显示回调（必须在开始推流之前设置）
      this.webRTC.onStreamStarted = (streamId) => {
        console.log("收到直播间ID:", streamId);
        this.showStreamInfo(streamId);
      };

      // 开始推流
      await this.webRTC.startStreaming(this.localStream);

      this.isStreaming = true;
      this.startBtn.disabled = true;
      this.stopBtn.disabled = false;
      this.updateStatus("streaming", "直播中");

      console.log("开始直播成功");
    } catch (error) {
      console.error("开始直播失败:", error);
      this.updateStatus("error", "直播失败: " + error.message);
      alert("无法开始直播: " + error.message);
    }
  }

  // 停止直播
  async stopStreaming() {
    try {
      // 停止本地流
      if (this.localStream) {
        this.localStream.getTracks().forEach((track) => track.stop());
        this.localStream = null;
      }

      this.webRTC.stopStreaming();

      this.isStreaming = false;
      this.startBtn.disabled = false;
      this.stopBtn.disabled = true;
      this.updateStatus("ready", "准备就绪");
      this.hideStreamInfo();

      console.log("停止直播成功");
    } catch (error) {
      console.error("停止直播失败:", error);
    }
  }

  // 切换摄像头
  async toggleCamera() {
    try {
      if (!this.localStream) {
        alert("请先开始直播");
        return;
      }

      this.currentCamera =
        this.currentCamera === "user" ? "environment" : "user";

      // 停止当前流
      this.localStream.getTracks().forEach((track) => track.stop());

      // 获取新的摄像头流
      this.localStream = await this.getCameraStream();
      this.localVideo.srcObject = this.localStream;

      // 如果正在直播，更新流
      if (this.isStreaming) {
        await this.webRTC.updateStream(this.localStream);
      }

      console.log("切换摄像头成功:", this.currentCamera);
    } catch (error) {
      console.error("切换摄像头失败:", error);
      alert("切换摄像头失败: " + error.message);
    }
  }

  // 加入直播间
  async joinStream() {
    try {
      const streamId = this.streamUrl.value.trim();
      if (!streamId) {
        alert("请输入直播间ID");
        return;
      }

      // 防止用户加入自己的直播间
      if (this.isStreaming && this.webRTC.streamId === streamId) {
        alert("不能加入自己的直播间！请在另一个浏览器窗口中观看。");
        return;
      }

      this.updateStatus("connecting", "连接直播间...");

      // 先连接到服务器
      if (!this.webRTC.isConnected) {
        console.log("连接到WebSocket服务器...");
        await this.webRTC.connect();
      }

      // 设置错误处理回调
      this.webRTC.onError = (error) => {
        console.error("WebRTC错误:", error);
        this.updateStatus("error", "连接失败: " + error);
        alert("连接失败: " + error);
      };

      // 设置连接状态回调
      this.webRTC.onConnectionStateChange = (state) => {
        console.log("连接状态变化:", state);
        if (state === "connected") {
          this.updateStatus("connected", "P2P连接建立");
        } else if (state === "failed") {
          this.updateStatus("error", "P2P连接失败");
        }
      };

      // 设置流接收成功回调
      this.webRTC.onStreamReceived = () => {
        console.log("视频流接收成功!");
        this.updateStatus("streaming", "正在观看直播");

        // 如果视频仍然暂停，显示手动播放提示
        setTimeout(() => {
          if (this.remoteVideo.paused) {
            console.log("⚠️ 视频需要手动播放");
            this.updateStatus("ready", "视频已接收，请点击播放按钮");
            this.showPlayPrompt();
          } else {
            this.hidePlayPrompt();
          }
        }, 1000);
      };

      console.log("开始加入直播间...");
      await this.webRTC.joinStream(streamId, this.remoteVideo);

      this.joinBtn.disabled = true;
      this.leaveBtn.disabled = false;
      this.updateStatus("connected", "已连接直播间");

      // 添加超时检查
      setTimeout(() => {
        if (!this.webRTC.remoteStream) {
          console.warn("⚠️ 10秒后仍未收到视频流，可能存在问题");
          console.log(
            "PeerConnection状态:",
            this.webRTC.peerConnection?.connectionState
          );
          console.log(
            "ICE连接状态:",
            this.webRTC.peerConnection?.iceConnectionState
          );
        }
      }, 10000);

      console.log("加入直播间成功:", streamId);
    } catch (error) {
      console.error("加入直播间失败:", error);
      this.updateStatus("error", "连接失败");
      alert("无法连接直播间: " + error.message);
    }
  }

  // 离开直播间
  async leaveStream() {
    try {
      this.webRTC.leaveStream();

      this.remoteVideo.srcObject = null;
      this.hidePlayPrompt();
      this.joinBtn.disabled = false;
      this.leaveBtn.disabled = true;
      this.updateStatus("ready", "准备就绪");

      console.log("离开直播间成功");
    } catch (error) {
      console.error("离开直播间失败:", error);
    }
  }

  // 获取摄像头流
  async getCameraStream() {
    const constraints = {
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: this.currentCamera,
      },
      audio: true,
    };

    try {
      return await navigator.mediaDevices.getUserMedia(constraints);
    } catch (error) {
      // 如果指定的摄像头不可用，尝试默认摄像头
      if (error.name === "OverconstrainedError") {
        const fallbackConstraints = {
          video: true,
          audio: true,
        };
        return await navigator.mediaDevices.getUserMedia(fallbackConstraints);
      }
      throw error;
    }
  }

  updateStatus(type, message) {
    this.status.textContent = message;
    this.status.className = type;
  }

  showStreamInfo(streamId) {
    console.log("showStreamInfo被调用，streamId:", streamId);
    this.currentStreamId.textContent = streamId;
    this.streamInfo.style.display = "block";
    console.log("直播间信息已显示");
  }

  hideStreamInfo() {
    this.streamInfo.style.display = "none";
    this.currentStreamId.textContent = "";
  }

  async copyStreamIdToClipboard() {
    try {
      const streamId = this.currentStreamId.textContent;
      await navigator.clipboard.writeText(streamId);
      alert("直播间ID已复制到剪贴板: " + streamId);
    } catch (error) {
      console.error("复制失败:", error);
      // 备用方案：选择文本
      const range = document.createRange();
      range.selectNode(this.currentStreamId);
      window.getSelection().removeAllRanges();
      window.getSelection().addRange(range);
      alert("请手动复制选中的直播间ID");
    }
  }

  async manualPlayVideo() {
    try {
      console.log("🎬 用户点击手动播放");
      await this.remoteVideo.play();
      console.log("✅ 手动播放成功！");
      this.hidePlayPrompt();
      this.updateStatus("streaming", "正在观看直播");
    } catch (error) {
      console.error("❌ 手动播放失败:", error);
      alert("播放失败：" + error.message);
    }
  }

  showPlayPrompt() {
    console.log("📺 显示手动播放提示");
    this.playPrompt.style.display = "block";
  }

  hidePlayPrompt() {
    console.log("🙈 隐藏手动播放提示");
    this.playPrompt.style.display = "none";
  }

  cleanup() {
    if (this.localStream) {
      this.localStream.getTracks().forEach((track) => track.stop());
    }
    this.webRTC.disconnect();
  }
}

// 页面加载完成后初始化应用
document.addEventListener("DOMContentLoaded", () => {
  // 检查浏览器支持
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    alert("您的浏览器不支持摄像头访问功能，请使用现代浏览器");
    return;
  }

  // 初始化应用
  window.liveStreamApp = new LiveStreamApp();
});
